<template>
  <su-popup
    v-model:show="state.show_popup"
    position="bottom"
    :round="15"
    :overlay="true"
    @close="handlePopupChange"
  >
    <view class="header-length">
      <view class="left-box">{{state.commonTootalNum}}条评论</view>
      <view class="right-content">
        <view
          class="enlarge-box"
          @click="emlargeCli"
        >
          <image
            src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250401/78fb4a3ca0ded3238c459ee372d812f2.png"
            mode="scaleToFill"
            class="img-style"
            v-if="state.height==80"
          />
          <image
            src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250401/ddbcda275409dbad153f98ca46bf18e7.png"
            mode="scaleToFill"
            class="img-style"
            v-else
          />
        </view>
        <view
          class="right-box"
          @click="close"
        >
          <image
            src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250401/31cfed9ceb02e2e76d63e78c09da5f82.png"
            mode="scaleToFill"
            class="img-style"
          />
        </view>
      </view>
    </view>
    <view
      class="popup-wrapper"
      :class="[customClass, `popup-${type}`]"
      :style="{ height: state.height + 'vh' }"
    >
      <scroll-view
        style="height: 100%"
        scroll-y
        class="friend-list"
        @scrolltolower="loadmore"
        v-if="state.comment.length"
      >
        <view
          v-for="(item,index) in state.comment"
          :key="index"
          class="comment-user"
        >
          <div class="user_info paddi-bomStyle">
            <div class="user-left-info">
              <image
                class="comment-user-info-avatar"
                :src="item.user.avatar ? cdnUrl(item.user.avatar) : 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250416/e7a91c64184dcd5646b290bf14be3b86.png'"
              >
              </image>
              <view class="user-info-text">
                <view class="user-info-text-name ss-flex align-baseline">
                  {{item.user.nickname}}
                </view>
                <view class="user-info-text-content">{{item.content}}</view>
                <view class="user-info-text-time">{{item.createtime}}
                  <text
                    @click="reply(item)"
                    class="repay-color"
                  > 回复 </text>
                </view>
              </view>
            </div>
            <view class="comment-like ss-flex flex-column">
              <view @click="likes_comment(item,index,'one')">
                <uni-icons
                  v-if="item.is_likes==1"
                  type="heart-filled"
                  size="28"
                  :color="'#E43B3D'"
                ></uni-icons>
                <uni-icons
                  v-if="item.is_likes==0"
                  type="heart-filled"
                  size="28"
                  :color="'#6C6E6D'"
                ></uni-icons>
              </view>
              <view class="comment-like-text">{{item.likes}}</view>
            </view>
          </div>
          <view
            class="user_info paddi-bomStyleOne"
            v-for="(value,page) in siliceFun(item)"
            :key="value.id"
          >
            <view class="comment-user-box ss-flex justify-between align-center">
              <view class="comment-user-info comment-user-infoCon ss-flex align-start">
                <image
                  class="comment-user-info-avatar"
                  :src="value.user.avatar ? cdnUrl(value.user.avatar) : 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250416/e7a91c64184dcd5646b290bf14be3b86.png'"
                >
                </image>
                <view class="user-info-text">
                  <view
                    class="user-info-text-name ss-flex align-baseline ss-font-24"
                    style="color:#767676;"
                  >
                    {{item.user.nickname}}
                    &nbsp;&nbsp;
                    <image
                      src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250407/0a696eac0a5b6789a7ec8f0f2cbcef45.png"
                      mode="scaleToFill"
                      class="img-style-size"
                    />
                    &nbsp;&nbsp;
                    {{value.user.to_nickName}}：
                  </view>
                  <view
                    class="user-info-text-content"
                    style="font-size: 24rpx;"
                  >

                    <!-- <text style="color:#767676;">
                      回复{{value.to_nickName}}：
                    </text> -->
                    <text>{{value.content}}</text>
                  </view>
                  <view class="user-info-text-time">{{value.createtime}} <text
                      @click="reply(item)"
                      class="repay-color"
                    >回复</text>
                  </view>
                </view>
              </view>
              <view class="comment-like ss-flex flex-column">
                <view @click="likes_comment(value,{index:index,page:page},'two')">
                  <uni-icons
                    v-if="value.is_likes==1"
                    type="heart-filled"
                    size="28"
                    :color="'#E43B3D'"
                  ></uni-icons>
                  <uni-icons
                    v-if="value.is_likes==0"
                    type="heart-filled"
                    size="28"
                    :color="'#6C6E6D'"
                  ></uni-icons>
                </view>
                <view class="comment-like-text">{{value.likes}}</view>
              </view>
            </view>
          </view>
          <view
            class="comment-omit"
            v-if="item.replyList.length"
          >
            <view class="sloid-style"></view>
            <div
              v-if="!item.expand"
              @click="expand(index)"
              class="row-flx"
            >{{item.expand ? '收起' : '展开'}}{{item.child.length}}条回复
              <image
                src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250331/3a9ebe59bcc7fb72c7d9684db643b996.png"
                mode="scaleToFill"
                class="img-size"
              />
            </div>
            <div
              @click="moreCli(index)"
              class="row-flx"
              v-if="item.expand&&item.child.length>item.replyList.length"
            >
              展开更多
              <image
                src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250331/3a9ebe59bcc7fb72c7d9684db643b996.png"
                mode="scaleToFill"
                class="img-size"
              />
            </div>
            <div
              class="close-box row-flx"
              v-if="item.expand"
              @click="closeMore(index)"
            >
              收起
              <image
                src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250401/0b43ccc8bed0ffa9203c83e7c202abf3.png"
                mode="scaleToFill"
                class="img-size"
              />
            </div>

          </view>
        </view>
      </scroll-view>
      <view
        v-else
        style="color: #999;text-align: center; margin-top: 20rpx;"
      >暂无评论</view>
    </view>
    <view class="input-box ">
      <div class="input-content">
        <view class="input-box">
          <input
            type="text"
            v-model="state.comment_text"
            :focus="state.focus"
            confirm-type='send'
            cursor-spacing="85rpx"
            :always-embed="true"
            placeholder-style="color:#A8A8A8;font-size:26rpx"
            :placeholder="state.placeholder"
            @blur="blur"
            @focus="onInputFocus"
            @input="inputChange"
            :cursor="cursorPos"
          />
          <view
            class="search_btn"
            @tap="inputCom"
          >发送</view>
        </view>

        <!-- <view
          class="emioBox"
          @click.stop="emioCli"
        >
          <image
            src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250401/578579e3a4cef0ce9494125f45975a61.png"
            mode="scaleToFill"
            class="emio-style"
            v-if="!state.emioShow"
          />
          <image
            src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250331/3a9ebe59bcc7fb72c7d9684db643b996.png"
            mode="scaleToFill"
            class="emio-styleOne"
            v-else
          />
        </view> -->
      </div>

      <div
        v-if="state.emioShow"
        class="emioShow-style"
      >
        <emoKeyboard
          :show="state.emioShow"
          @change="change"
          @delMsg="delMsg"
        ></emoKeyboard>
      </div>
    </view>

  </su-popup>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue';
import {
  cdnUrl
} from '@/association/utils'
import _ from 'lodash';
import emoKeyboard from '@/components/emoKeyboard.vue';
import assNavbar from '@/components/ass-navbar.vue'
import sheep from '@/sheep';
import API from '../../../../../api'
import association from '@/association/store'
const props = defineProps({
  // 弹窗类型：center(居中)/bottom(底部)/top(顶部)/message(消息提示)
  type: {
    type: String,
    default: 'center'
  },
  // 标题
  title: String,
  // 内容
  content: String,
  // 是否显示取消按钮
  showCancel: {
    type: Boolean,
    default: true
  },
  // 取消按钮文本
  cancelText: {
    type: String,
    default: '取消'
  },
  // 确认按钮文本
  confirmText: {
    type: String,
    default: '确定'
  },
  // 是否显示按钮区域
  showButtons: {
    type: Boolean,
    default: true
  },
  // 点击遮罩是否关闭
  maskClose: {
    type: Boolean,
    default: true
  },
  // 遮罩背景色
  maskBgColor: {
    type: String,
    default: '#fff'
  },
  // 自定义类名
  customClass: String
});
const state = reactive({
  height: 0,
  comment: [],
  assistants: null,
  id: '',
  comment_text: '',
  focus: false,
  placeholder: '发表您的看法',
  comment_id: 0,
  to_user_id: 0,
  loadStatus: '',
  pagination: {
    data: [],
    current_page: 0,
    total: 1,
    last_page: 1,
  },
  pageList: [],
  emioShow: false,
  selectionStart: 0,  // 光标起始位置
  selectionEnd: 0, // 光标结束位置
  cursorPos: 0, //光标位置
  lastCursorPos: 0, //最后一次光标的输入位置
  show_popup: false,
  commonTootalNum: 0
})
const emit = defineEmits(['cancel', 'close', 'open']);

const popupRef = ref(null);
const onInputFocus = (e) => {
  state.emioShow = false
}

const onInput = (e) => {

}
const handlePopupChange = (e) => {
  // 弹窗关闭时的处理逻辑
  // this.onPopupClosed()
  state.show_popup = false
  state.comment = []
  state.emioShow = false
}
// 点击表情
const emioCli = () => {
  if (state.emioShow) {
    // 关闭表情面板，自动聚焦输入框
    state.emioShow = false;
    nextTick(() => {
      state.focus = true;
    });
  } else {
    // 隐藏系统键盘，打开表情面板
    uni.hideKeyboard({
      success: () => {
        state.emioShow = true;
      }
    });
  }
}
// 核心方法：在光标位置插入内容
const insertContentAtCursor = (content) => {
  const { comment_text, lastCursorPos } = state;
  if (lastCursorPos === -1) return; // 无光标时忽略

  // 拼接新内容
  const newValue =
    comment_text.slice(0, lastCursorPos) +
    content +
    comment_text.slice(lastCursorPos);

  // 计算新光标位置
  const newCursorPos = lastCursorPos + content.length;

  // 更新输入框内容和光标位置
  state.comment_text = newValue

  state.cursorPos = newCursorPos
  state.lastCursorPos = newCursorPos
  // 兼容性修复：安卓可能需要异步更新
  setTimeout(() => {
    state.cursorPos = newCursorPos
  }, 10);
}
const inputChange = (e) => {
  // console.log('触发');

  // state.comment_text = e.detail.value
  // state.lastCursorPos = e.detail.cursor
  // insertContentAtCursor(state.comment_text);
}
// 选择图标
const change = (item) => {
  insertContentAtCursor(item);
}
// 删除
const delMsg = () => {
  const { selectionStart, selectionEnd, comment_text, cursorPos } = state;
  const charsBeforeCursor = Array.from(comment_text.slice(0, cursorPos));
  charsBeforeCursor.pop();
  const newText = charsBeforeCursor.join('') + comment_text.slice(cursorPos);
  state.comment_text = newText;
  // state.selectionStart = selectionStart - 1;
  // state.selectionEnd = selectionStart - 1;
  // // 无选中文本时，删除前一个字符
  // if (selectionStart === selectionEnd && selectionStart > 0) {
  //   const charsBeforeCursor = Array.from(comment_text.slice(0, selectionStart));
  //   charsBeforeCursor.pop(); // 删除最后一个字符（Unicode 安全）
  //   const newText = charsBeforeCursor.join('') + comment_text.slice(selectionStart);

  //   state.comment_text = newText;
  //   state.selectionStart = selectionStart - 1;
  //   state.selectionEnd = selectionStart - 1;
  // }
  // // 删除选中文本
  // else if (selectionStart !== selectionEnd) {
  //   state.comment_text = comment_text.slice(0, selectionStart) + comment_text.slice(selectionEnd);
  //   state.selectionStart = selectionStart;
  //   state.selectionEnd = selectionStart;
  // }
}
const expand = (index) => {
  state.comment[index].expand = !state.comment[index].expand
  console.log(state.comment[index]);

}
//加载更多
const moreCli = (index) => {
  const nextChunk = state.comment[index].child.slice(state.comment[index].currentIndex, state.comment[index].currentIndex + 10);
  state.comment[index].replyList = [...state.comment[index].replyList, ...nextChunk];
  state.comment[index].currentIndex += 10;
}
// 收起
const closeMore = (index) => {
  state.comment[index].replyList = [...state.comment[index].child].splice(0, 10);
  state.comment[index].expand = !state.comment[index].expand
  // item.expand = !item.expand
}

// 回复
const reply = (item) => {
  console.log(item, '回复');


  state.focus = true
  state.placeholder = `回复：${item.user.nickname} : 评论`
  state.comment_id = item.id
  state.to_user_id = item.user_id
}

// 打开弹窗
const open = (type, params, height = 50) => {
  console.log(params);

  state.show_popup = true
  // popupRef.value.open(type || props.type);
  state.height = height;
  state.commonTootalNum = params.commonTootalNum
  if (params) {
    state.id = params.find_id
    getList()
  }
  // emit('open');
};
const blur = (e) => {
  console.log(e, '失去焦点');

  if (!state.emioShow) {
    state.focus = false
    state.placeholder = `发表您的看法`
    state.comment_text = state.comment_text ? state.comment_text : ''
    state.comment_id = 0
    state.to_user_id = 0
  }
}
watch(() => state.pageList, (newVal) => {
  nextTick(() => {
    state.comment = newVal.map(item => ({
      replyList: item.child.length && item.child.length > 10 ? [...item.child].splice(0, 10) : item.child,
      ...item,
      child: reactive(item.child),
      currentIndex: 10
    }))

  })
})
function debounce (fn, time) {
  let timeout = null
  return function (...args) {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      console.log('执行防抖22222');

      fn.call(this, ...args)
    }, time)
  }
}
const inputCom = () => {
  // 执行防抖
  debounce(confirm(), 1000)
}
// 发表评论
const confirm = async () => {
  if (!state.comment_text) {
    return
  }
  let params = {
    assistant_id: state.assistants.assistant_id,
    comment_id: state.comment_id, // 如果是回复就是被回复的id 
    content: state.comment_text,
    find_id: state.assistants.assistant_id,
    to_user_id: state.to_user_id
  }
  const res = await API.findComment(params)
  if (res.code == 1) {
    console.log(res, '评论成功');

    state.focus = false
    state.placeholder = `发表您的看法`
    state.comment_text = ''
    state.comment_id = 0
    state.to_user_id = 0
    uni.$emit('commentSet', {
      find_id: params.find_id
    })
    // 请求评论条数
    association().commonTootal({ find_id: state.id })
    uni.showToast({
      icon: 'none',
      title: '评论成功',
      duration: 1000,
    });
    // state.comment = [];
    getList(state.pagination.current_page, 'find', 'concat')

  }

}
const getList = async (page = 1, type = 'find', status) => {
  // let list = []
  state.loadStatus = 'loading';
  //获取评论列表
  const {
    code,
    data
  } = await API.findCommentList({
    find_id: state.id,
    page,
    type
  });
  if (code === 1) {
    const dataList = data.data.map(item => {
      return {
        expand: false,
        ...item
      }
    })
    if (data.current_page === 1) {
      state.pageList = dataList
    } else {
      state.pageList = [...state.pageList, ...dataList]
    }
    state.assistants = data;
    state.pagination.current_page = data.current_page
    state.pagination.last_page = data.last_page
    if (data.current_page < data.last_page) {
      state.loadStatus = 'more';
    } else {
      state.loadStatus = 'noMore';
    }
  }
}
const likes_comment = async (item, index, type) => {
  if (state.throttle) {
    return
  }
  state.throttle = true
  let res = await API.findCommentLike({
    comment_id: item.id,
  });
  state.throttle = false
  if (res.code) {
    // 一级评论
    if (type === 'one') {
      if (res.data.is_like) {
        state.comment[index].likes += 1;
      } else {
        state.comment[index].likes -= 1;
      }
      state.comment[index].is_likes = res.data.is_like
    } else {
      // 二级评论
      state.comment[index.index].child[index.page].is_likes = res.data.is_like
      if (state.comment[index.index].child[index.page].is_likes) {
        state.comment[index.index].child[index.page].likes += 1;
      } else {
        state.comment[index.index].child[index.page].likes -= 1;
      }
    }
  }
}
const siliceFun = (item) => {

  return item.replyList.slice(0, item.expand ? item.replyList.length : 0)
}
// 关闭弹窗
const close = () => {
  // popupRef.value.close();
  state.show_popup = false
  state.emioShow = false
  emit('close');
};

// 放大
const emlargeCli = () => {
  state.height = state.height == 50 ? 80 : 50
}
// 加载更多
function loadmore () {
  if (state.pagination.current_page >= state.pagination.last_page) {
    state.loadStatus = 'noMore'
    return
  } else {
    state.pagination.current_page++
    getList(state.pagination.current_page, 'find')
  }
}

// 上拉加载更多
// onReachBottom(() => {
//   console.log('加载');

//   loadmore();
// });
// 暴露方法给父组件
defineExpose({
  open,
  close
});
</script>

<style lang="scss" scoped>
// view {
//   flex-direction: row;
// }
.emioShow-style {
  width: 100%;
}
.empty-box {
  padding-top: 0 !important;
}
.paddi-bomStyle {
  padding-bottom: 34rpx !important;
}
.comment-omit {
  display: flex;
  align-items: center;
  flex-direction: row;
  margin-left: 120rpx;
  font-size: 24rpx;
  color: #848487;
  line-height: 42px;
  .sloid-style {
    width: 38rpx;
    height: 2rpx;
    background: #d8d8d8;
    margin-right: 16rpx;
  }
  .img-size {
    width: 16rpx;
    height: 10rpx;
    margin-left: 6rpx;
  }
  .close-box {
    margin-left: 20rpx;
  }
  .row-flx {
    flex-direction: row !important;
    align-items: center !important;
  }
}
.header-length {
  width: 100%;
  text-align: center;
  font-size: 24rpx;
  color: #3d3d3d;
  margin-top: 24rpx;
  margin-bottom: 24rpx;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  height: 100%;
  .left-box {
    flex: 1;
    display: flex;
    justify-content: center;
  }
  .right-content {
    flex-direction: row;
    position: absolute;
    right: 22rpx;
  }
  .enlarge-box {
    width: 48rpx;
    height: 48rpx;
    background: #f3f3f5;
    margin-right: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10rpx;
    border-radius: 6rpx;
    .img-style {
      width: 50%;
      height: 50%;
    }
  }
  .right-box {
    width: 48rpx;
    height: 48rpx;
    border-radius: 50%;
    background: #f3f3f5;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10rpx;
    .img-style {
      width: 50%;
      height: 50%;
    }
  }
}
.user_info {
  width: 100%;
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  padding: 0 30rpx 0 30rpx;
  box-sizing: border-box;
  flex: 1;
  .user-left-info {
    display: flex;
    flex-direction: row;
  }
  .comment-user-infoCon {
    margin-left: 84rpx;
    flex-direction: row;
  }
  .comment-user-box {
    flex-direction: row;
    width: 100%;
    color: #e43b3d;
    padding: 20rpx 0 16rpx 0;
  }
  .comment-user-info-avatar {
    width: 70rpx;
    height: 70rpx;
    border-radius: 50%;
    margin-right: 16rpx;
  }
  .user-info-text {
    flex: 1;

    .user-info-text-name {
      line-height: 42rpx;
      font-weight: normal;
      color: #b4b3b5;
      font-size: 24rpx;
      .img-style-size {
        width: 16rpx;
        height: 16rpx;
      }
    }

    .user-info-text-content {
      font-size: 24rpx;
      font-weight: normal;
      color: #3d3d3d;
      margin-top: 5rpx;
    }

    .user-info-text-time {
      font-size: 24rpx;
      font-weight: normal;
      color: #b4b3b5;
      line-height: 42rpx;
      margin-top: 5rpx;
      flex-direction: row;
      .repay-color {
        color: #003ad9 !important;
        margin-left: 10rpx;
      }
    }
  }
  .comment-like {
    margin-left: 10rpx;
    // justify-content: center;
    flex-direction: row !important;
    align-items: center !important;
    .comment-like-text {
      font-size: 28rpx;
      font-weight: normal;
      text-align: center;
      color: #6c6e6d;
    }
  }
}
.popup-wrapper {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: auto;
  padding-bottom: 100rpx;

  &.popup-center {
    width: 100%;
  }

  &.popup-bottom {
    width: 100%;
    border-radius: 24rpx 24rpx 0 0;
  }

  &.popup-top {
    width: 100%;
    border-radius: 0 0 24rpx 24rpx;
  }
}

.popup-content {
  padding: 40rpx;
}

.popup-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  text-align: center;
}

.popup-message {
  display: block;
  font-size: 32rpx;
  color: #666;
  margin-bottom: 40rpx;
  text-align: center;
}

.popup-buttons {
  display: flex;
  justify-content: space-between;

  .popup-button {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 32rpx;
    border-radius: 8rpx;
    margin: 0 10rpx;

    &.cancel {
      background-color: #f5f5f5;
      color: #333;
    }

    &.confirm {
      background-color: #2979ff;
      color: #fff;
    }
  }
}
.emoKeyboard-box {
  padding-bottom: 60rpx;
}
.input-box {
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 99;
  background-color: #fff;
  display: flex;
  align-items: center;
  :deep(.uni-input-wrapper) {
    width: 93% !important;
  }
  .input-content {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding-top: 10rpx !important ;
    background-color: #fff;
    transition: all 0.3s ease;

    .input-box {
      flex-direction: row;
      position: relative;
      width: 90%;
    }
    .search_btn {
      background-color: #2a6dde;
      padding: 3rpx;
      color: #fff;
      height: 46rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 40rpx;
      font-size: 30rpx;
      margin-left: 20rpx;
      flex: 1;
      margin-bottom: 26rpx;
    }
  }
  .emioBox {
    position: absolute;
    right: 40rpx;
    top: 28rpx;
    width: 40rpx !important;
    height: 40rpx !important;
    z-index: 999 !important;
    pointer-events: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    // background-color: red;
    .emio-style {
      width: 100%;
    }
    .emio-styleOne {
      width: 70%;
      height: 50%;
    }
  }

  input {
    width: 84%;
    height: 80rpx;
    border-radius: 10rpx;
    background: #eeeeee;
    padding: 0 20rpx;
    box-sizing: border-box;
    margin-bottom: 30rpx;
  }
}
</style>